import { Epic, ofType } from "redux-observable";

import { from, of } from "rxjs";
import { fromPromise } from "rxjs/internal-compatibility";
import { catchError, flatMap, map, switchMap } from "rxjs/operators";

import { wrapLoading } from "../../../../shared/api";
import { adminService } from "../../services/admin.service";
import {
  ActionNil,
  ActionSetLoading,
  ActionSetQuery,
  ActionSetRoleList,
  ActTypes
} from "./actions";

const getRoleListAsyncEpic: Epic = action$ =>
  action$.pipe(
    ofType(ActTypes.GetRoleListAsync),
    // pluck('payload'),
    map(action => action.payload),
    switchMap(({ query, pn, ps }) => {
      const api$ = fromPromise(
        adminService.getRoleList({ query, pn, ps })
      ).pipe(
        flatMap(res => {
          return from([
            { ...new ActionSetQuery(query) },
            { ...new ActionSetRoleList(res.data) }
          ]);
        }),
        catchError(() => of({ ...new ActionNil() }))
      );
      return wrapLoading(api$, "roleList", ActionSetLoading);
    })
  );

export const epics: Epic[] = [getRoleListAsyncEpic];
